#!/bin/bash

echo "=========================================="
echo "   Fried衰弱评估问卷系统 - 启动脚本"
echo "=========================================="
echo

# 检查并终止占用端口的进程
echo "1. 检查并终止占用端口的进程..."
if lsof -Pi :13000 -sTCP:LISTEN -t >/dev/null 2>&1; then
    echo "终止占用端口13000的进程..."
    lsof -Pi :13000 -sTCP:LISTEN -t | xargs kill -9 2>/dev/null
fi

if lsof -Pi :8081 -sTCP:LISTEN -t >/dev/null 2>&1; then
    echo "终止占用端口8081的进程..."
    lsof -Pi :8081 -sTCP:LISTEN -t | xargs kill -9 2>/dev/null
fi

echo
echo "2. 安装Python依赖..."
pip install -r requirements.txt

echo
echo "3. 启动FastAPI后端服务器 (端口13000)..."
nohup python main.py > backend.log 2>&1 &
BACKEND_PID=$!
echo "后端进程ID: $BACKEND_PID"

echo
echo "4. 等待后端启动..."
sleep 5

echo
echo "5. 启动Vue前端应用 (端口8081)..."
nohup npm run serve -- --host 0.0.0.0 --port 8081 > frontend.log 2>&1 &
FRONTEND_PID=$!
echo "前端进程ID: $FRONTEND_PID"

echo
echo "=========================================="
echo "系统启动完成！"
echo
echo "前端地址: http://localhost:8081"
echo "后端API: http://localhost:13000"
echo "API文档: http://localhost:13000/docs"
echo
echo "进程信息:"
echo "后端PID: $BACKEND_PID"
echo "前端PID: $FRONTEND_PID"
echo
echo "日志文件:"
echo "后端日志: backend.log"
echo "前端日志: frontend.log"
echo
echo "使用说明:"
echo "1. 在前端填写问卷并保存"
echo "2. 点击\"导出数据\"按钮"
echo "3. 输入密码: admin123"
echo "4. 下载压缩包"
echo
echo "停止服务: kill $BACKEND_PID $FRONTEND_PID"
echo "=========================================="